package com.csc.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.csc.domain.SystemAccount;
import com.csc.domain.SystemStatus;
import com.csc.domain.SystemTimeUsed;
import com.csc.domain.TransactionHistory;
import com.csc.service.SystemAccountService;
import com.csc.service.SystemStatusService;
import com.csc.service.SystemTransactionHistoryService;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import constants.Constant;

@Controller
@SessionAttributes("user")
public class SystemAdminController {
	@Autowired
	SystemTransactionHistoryService transactionHistoryService;

	@Autowired
	SystemAccountService sysAccSer;

	@Autowired
	SystemStatusService sysSttSer;
	static final Logger logger = Logger.getLogger(SystemAdminController.class);

	/**
	 * @author vuhuynh
	 * @param model
	 * @return
	 * 
	 *         Get List history transaction, show complete/ reject request of
	 *         account admin, account support, report support
	 * 
	 */
	@RequestMapping(value = "/adminViewAccountRequest", method = RequestMethod.GET)
	public String getListTransaction() {
		return "admin/listrequests";
	}

	/**
	 * JSON view Account Request using JSON
	 * 
	 * @return
	 */
	@RequestMapping(value = "/adminViewAccountRequestJSON")
	@ResponseBody
	public List<TransactionHistory> getListTransactionJSON() {

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.getListTransactionRequestByAccount();

		return listTransHistory;
	}

	/**
	 * JSON Request Search By Name using JSON
	 * 
	 * @return
	 */
	
	@RequestMapping(value = "/searchAccountRequestTransactionByNameJSON/{name}", method = RequestMethod.POST)
	@ResponseBody
	public List<TransactionHistory> searchAccountRequestTransactionByNameJSON(
			@PathVariable("name") String name) {

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.searchAccountRequestTransactionByName(name);

		return listTransHistory;
	}

	/**
	 * JSON Request Search Advance using JSON
	 * 
	 * @return
	 */

	@RequestMapping(value = "/searchAccountRequestTransactionAdvanceJSON/{accImp}/{accAff}/{fromDate}/{toDate}/{role}/{status}", method = RequestMethod.POST)
	@ResponseBody
	public List<TransactionHistory> searchAccountRequestTransactionAdvanceJSON(
			@PathVariable("accImp") String accImpact,
			@PathVariable("accAff") String accAffected,
			@PathVariable("fromDate") String fromDate,
			@PathVariable("toDate") String toDate,
			@PathVariable("role") String role,
			@PathVariable("status") String status) {

		if (accImpact.equals("null")) {
			accImpact = "";
		}
		if (accAffected.equals("null")) {
			accAffected = "";
		}
		if (toDate.equals("null")) {
			toDate = "2014-09-30 00:00:00";
		} else {
			toDate += " 00:00:00";
		}
		if (fromDate.equals("null")) {
			fromDate = "2014-07-30 00:00:00";
		} else {
			fromDate += " 00:00:00";
		}

		if (role.equals("null")) {
			role = "(p.accImpact.systemAccountType.typeName = 'Account Admin' "
					+ "OR p.accImpact.systemAccountType.typeName = 'Account Support' "
					+ "OR p.accImpact.systemAccountType.typeName = 'Report Support')";
		} else {
			role = "p.accImpact.systemAccountType.typeName = '" + role + "' ";
		}
		if (status.equals("null")) {
			status = "p.systemStatus =" + constants.Constant.STATUS_ID_COMPLETE
					+ " OR p.systemStatus="
					+ constants.Constant.STATUS_ID_REJECTS + " ";
		} else {

			status = "p.systemStatus = " + status;
		}
		List<TransactionHistory> listTransHistory = transactionHistoryService
				.searchAccountRequestTransactionAdvance(accImpact, accAffected,
						fromDate, toDate, role, status);
		return listTransHistory;
	}

	@RequestMapping(value = "/adminViewReportAction")
	public String viewReportAction(Model model) {

		return "admin/blogrequests";
	}

	/**
	 * JSON admin View Report Action using JSON
	 * 
	 * @return
	 */

	@RequestMapping(value = "/adminviewReportActionJSON")
	@ResponseBody
	public List<TransactionHistory> viewReportActionJSON() {

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.getListTransactionRequestByAdminReport();

		return listTransHistory;
	}

	@RequestMapping(value = "/adminViewReportActionBySearch")
	public String viewReportActionUsingUserName(
			@RequestParam("txtSearchByFirstName") String name, Model model) {

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.viewReportActionBySearchUsingUserName(name);
		model.addAttribute("listTransRequest", listTransHistory);
		// logger.info("" + listTransHistory.size());
		return "admin/blogrequests";
	}

	/**
	 * JSON search Report transaction By Name using JSON
	 * 
	 * @return
	 */
	@RequestMapping(value = "/viewReportActionUsingUserNameJSON/{name}", method = RequestMethod.POST)
	@ResponseBody
	public List<TransactionHistory> viewReportActionUsingUserNameJSON(
			@PathVariable("name") String name) {

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.viewReportActionBySearchUsingUserName(name);

		return listTransHistory;
	}

	@RequestMapping(value = "/adminViewReportActionByAdvanceSearch")
	public String viewReportActionUsingAdvanceSearch(
			@RequestParam("txtUserNameImpact") String accImpact,
			@RequestParam("txtUserNameAffected") String accAffected,
			@RequestParam("txtFromDate") String fromDate,
			@RequestParam("txtToDate") String toDate,
			@RequestParam("cbbRole") String role,
			@RequestParam("cbbStatus") String status, Model model) {

		if (toDate.equals("")) {
			toDate = "2014-09-30 00:00:00";
		} else {
			toDate += " 00:00:00";
		}
		if (fromDate.equals("")) {
			fromDate = "2014-07-30 00:00:00";
		} else {
			fromDate += " 00:00:00";
		}

		if (role.equals("")) {
			role = "(p.accImpact.systemAccountType.typeName = 'User Admin' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User Support' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User System')";
		} else {
			role = "p.accImpact.systemAccountType.typeName = '" + role + "' ";
		}
		if (status.equals("")) {
			status = "p.systemStatus =" + constants.Constant.STATUS_ID_COMPLETE
					+ " OR p.systemStatus="
					+ constants.Constant.STATUS_ID_REJECTS + " ";
		} else {

			status = "p.systemStatus = " + status;
		}

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.viewReportActionByAdvanceSearch(accImpact, accAffected,
						fromDate, toDate, role, status);
		model.addAttribute("listTransRequest", listTransHistory);

		// logger.info("" + listTransHistory.size());
		return "admin/blogrequests";
	}

	/**
	 * JSON Report Search Advance using JSON
	 * 
	 * @return
	 */

	@RequestMapping(value = "/viewReportActionUsingAdvanceSearchJSON/{accImp}/{accAff}/{fromDate}/{toDate}/{role}/{status}", method = RequestMethod.POST)
	@ResponseBody
	public List<TransactionHistory> viewReportActionUsingAdvanceSearchJSON(
			@PathVariable("accImp") String accImpact,
			@PathVariable("accAff") String accAffected,
			@PathVariable("fromDate") String fromDate,
			@PathVariable("toDate") String toDate,
			@PathVariable("role") String role,
			@PathVariable("status") String status) {

		if (accImpact.equals("null")) {
			accImpact = "";
		}
		if (accAffected.equals("null")) {
			accAffected = "";
		}
		if (toDate.equals("null")) {
			toDate = "2014-09-30 00:00:00";
		} else {
			toDate += " 00:00:00";
		}
		if (fromDate.equals("null")) {
			fromDate = "2014-07-30 00:00:00";
		} else {
			fromDate += " 00:00:00";
		}

		if (role.equals("null")) {
			role = "(p.accImpact.systemAccountType.typeName = 'User Admin' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User Support' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User System')";
		} else {
			role = "p.accImpact.systemAccountType.typeName = '" + role + "' ";
		}
		if (status.equals("null")) {
			status = "p.systemStatus =" + constants.Constant.STATUS_ID_COMPLETE
					+ " OR p.systemStatus="
					+ constants.Constant.STATUS_ID_REJECTS + " ";
		} else {

			status = "p.systemStatus = " + status;
		}
		List<TransactionHistory> listTransHistory = transactionHistoryService
				.viewReportActionByAdvanceSearch(accImpact, accAffected,
						fromDate, toDate, role, status);
		return listTransHistory;
	}

	@RequestMapping(value = "/generatePDF", method = RequestMethod.GET)
	public void downloadPDFReportTransaction(
			@RequestParam("txtUserNameImpact") String accImpact,
			@RequestParam("txtUserNameAffected") String accAffected,
			@RequestParam("txtFromDate") String fromDate,
			@RequestParam("txtToDate") String toDate,
			@RequestParam("cbbRole") String role,
			@RequestParam("cbbStatus") String status,
			HttpServletResponse response, HttpServletRequest request,
			Model model) {

		if (toDate.equals("")) {
			toDate = "2014-09-30 00:00:00";
		} else {
			toDate += " 00:00:00";
		}
		if (fromDate.equals("")) {
			fromDate = "2014-07-30 00:00:00";
		} else {
			fromDate += " 00:00:00";
		}

		if (role.equals("")) {
			role = "(p.accImpact.systemAccountType.typeName = 'User Admin' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User Support' "
					+ "OR p.accImpact.systemAccountType.typeName = 'User System')";
		} else {
			role = "p.accImpact.systemAccountType.typeName = '" + role + "' ";
		}
		if (status.equals("")) {
			status = "p.systemStatus =" + constants.Constant.STATUS_ID_COMPLETE
					+ " OR p.systemStatus="
					+ constants.Constant.STATUS_ID_REJECTS + " ";
		} else {

			status = "p.systemStatus = " + status;
		}

		List<TransactionHistory> listTransHistory = transactionHistoryService
				.viewReportActionByAdvanceSearch(accImpact, accAffected,
						fromDate, toDate, role, status);

		String orignalFileName = "Report.pdf";

		try {
			Document document = new Document();
			response.setHeader("Content-Disposition", "outline;filename=\""
					+ orignalFileName + "\"");
			PdfWriter.getInstance(document, response.getOutputStream());

			// image
			String realPath = request.getSession().getServletContext()
					.getRealPath("resources/main/img/logo.png");
			Image image = Image.getInstance(realPath);

			document.open();
			document.add(createFirstTable(listTransHistory, image));
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public PdfPTable createFirstTable(List<TransactionHistory> listTrans,
			Image image) throws ParseException, DocumentException, IOException {

		// a table with three columns
		PdfPTable table = new PdfPTable(6);
		table.setWidthPercentage(100);
		table.setWidths(new float[] { 0.5f, 2f, 3f, 2f, 3f, 2f });
		// the cell object
		PdfPCell cell;
		// we add a cell with colspan 3
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String timeAction = dateFormat.format(date);

		Font font1 = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLDITALIC);
		Font font2 = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
		Font font3 = new Font(Font.FontFamily.HELVETICA, 11, Font.NORMAL);
		Font font4 = new Font(Font.FontFamily.HELVETICA, 11, Font.NORMAL,
				BaseColor.GREEN);
		Font font5 = new Font(Font.FontFamily.HELVETICA, 11, Font.NORMAL,
				BaseColor.RED);

		// Add row CSC BANKING
		BaseColor colerBanner = new BaseColor(100, 100, 100);
		cell = new PdfPCell(new Phrase("CSC BANKING", font1));
		cell.setImage(image);
		cell.setBorderWidth(0);
		cell.setPaddingBottom(10);
		cell.setPaddingTop(5);
		cell.setBackgroundColor(colerBanner);
		cell.setColspan(6);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("  ", font1));
		cell.setBorderWidth(0);
		cell.setPadding(15);
		cell.setColspan(6);
		table.addCell(cell);

		// Add row Report and datime
		cell = new PdfPCell(new Phrase(
				"Report transaction history admin Action.", font2));
		cell.setBorderWidth(0);
		cell.setPaddingBottom(30);
		cell.setColspan(5);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(timeAction, font3));
		cell.setBorderWidth(0);
		cell.setPaddingBottom(30);
		cell.setColspan(1);
		table.addCell(cell);

		// iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6,
		// iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

		BaseColor coler = new BaseColor(100, 100, 100);
		cell = new PdfPCell(new Phrase("No"));
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);

		cell.setColspan(1);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("Admin"));
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);
		cell.setColspan(1);
		table.addCell(cell);

		/*
		 * cell = new PdfPCell(new Phrase("Role")); cell.setBorderWidthLeft(0);
		 * cell.setBorderWidthRight(0); cell.setBackgroundColor(coler);
		 * cell.setColspan(1); table.addCell(cell);
		 */

		cell = new PdfPCell(new Phrase("Task"));
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);
		cell.setColspan(1);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("User"));
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);
		cell.setColspan(1);
		table.addCell(cell);

		/*
		 * cell = new PdfPCell(new Phrase("Command"));
		 * cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0);
		 * cell.setBackgroundColor(coler); cell.setColspan(1);
		 * table.addCell(cell);
		 */

		cell = new PdfPCell(new Phrase("Date of Process"));
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);
		cell.setColspan(1);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("Status"));
		cell.setBorderWidthLeft(0);
		cell.setBorderWidthRight(0);
		cell.setBackgroundColor(coler);
		cell.setColspan(1);
		table.addCell(cell);

		for (TransactionHistory taskEntry : listTrans) {
			cell = new PdfPCell(new Phrase("" + taskEntry.getTransactionId()));
			cell.setPadding(0);
			cell.setColspan(1);
			table.addCell(cell);
			table.addCell(taskEntry.getAccImpact().getAccountLoginId());
			/*
			 * table.addCell(taskEntry.getAccImpact().getSystemAccountType().
			 * getTypeName());
			 */
			table.addCell(taskEntry.getActionTransaction());
			table.addCell(taskEntry.getAccAffected().getAccountLoginId());
			/* table.addCell(taskEntry.getCommand()); */

			table.addCell("" + taskEntry.getDateTransaction());
			if (taskEntry.getSystemStatus().getStatusName().equals("Complete")) {
				cell = new PdfPCell(new Phrase(taskEntry.getSystemStatus()
						.getStatusName(), font4));
				table.addCell(cell);
			} else {
				cell = new PdfPCell(new Phrase(taskEntry.getSystemStatus()
						.getStatusName(), font5));
				table.addCell(cell);
			}
		}
		return table;
	}

	@RequestMapping(value = "/adminActiveOrDisable", method = RequestMethod.POST)
	public String doActiveOrDisableUserAccount(
			@RequestParam("action") String action,
			@RequestParam("listCheckbox") String[] accAff, Model model,
			@ModelAttribute("user") String accImp) {

		System.out.println(" do dai: " + accAff.length);

		if (action.equals("Active")) {
			for (int i = 0; i < accAff.length; i++) {
				SystemAccount accIm = sysAccSer.getAccountByUsername(accImp);
				SystemAccount accAffec = sysAccSer
						.getAccountByUsername(accAff[i]);

				if (accIm.getSystemAccountType().getTypeId() > accAffec
						.getSystemAccountType().getTypeId()
						|| accAffec.getSystemStatus().getStatusId() == constants.Constant.STATUS_ID_ACTIVE) {

				} else {

					Date date = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							Constant.SIMPLE_DATE_FORMAT);
					String timeAction = dateFormat.format(date);

					SystemStatus sysStt = sysSttSer
							.getStatusByID(constants.Constant.STATUS_ID_COMPLETE);
					TransactionHistory trans = new TransactionHistory(
							timeAction, Constant.ACTION_ACTIVE_USER,
							Constant.ACTION_ACTIVE_USER);
					trans.setAccImpact(accIm);
					trans.setAccAffected(accAffec);
					trans.setSystemStatus(sysStt);
					sysAccSer.doActiveAccountByAdmin(trans, accAff[i],
							constants.Constant.STATUS_ID_ACTIVE);
				}

			}
		} else {
			for (int i = 0; i < accAff.length; i++) {
				SystemAccount accIm = sysAccSer.getAccountByUsername(accImp);
				SystemAccount accAffec = sysAccSer
						.getAccountByUsername(accAff[i]);
				if (accIm.getSystemAccountType().getTypeId() > accAffec
						.getSystemAccountType().getTypeId()
						|| accAffec.getSystemStatus().getStatusId() == constants.Constant.STATUS_ID_DISABLE) {

				} else {
					Date date = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							Constant.SIMPLE_DATE_FORMAT);
					String timeAction = dateFormat.format(date);
					SystemStatus sysStt = sysSttSer
							.getStatusByID(constants.Constant.STATUS_ID_COMPLETE);
					TransactionHistory trans = new TransactionHistory(
							timeAction, Constant.ACTION_DISABLE_USER,
							Constant.ACTION_DISABLE_USER);
					trans.setAccImpact(accIm);
					trans.setAccAffected(accAffec);
					trans.setSystemStatus(sysStt);
					sysAccSer.doActiveAccountByAdmin(trans, accAff[i],
							constants.Constant.STATUS_ID_DISABLE);
				}
			}
		}

		/*List<SystemAccount> list = sysAccSer.getRegisteredAccounts();
		model.addAttribute("listUsers", list);*/
		return "admin/listusers";
	}
	
	@RequestMapping(value = "/autoCompleteRequestTransactionAccountSearchName")
	@ResponseBody
	public HashSet<String> autoCompleteRequestTransactionAccountSearchName() {
		List<TransactionHistory> listAll = transactionHistoryService.getListTransactionRequestByAccount();
		HashSet<String> set = new HashSet<String>();

		for (TransactionHistory trans : listAll) {
			set.add(trans.getAccImpact().getAccountFirstName());
		}
		return set;
	}
	
	@RequestMapping(value = "/autoCompleteRequestTransactionAdminSearchName")
	@ResponseBody
	public HashSet<String> autoCompleteRequestTransactionAdminSearchName() {
		List<TransactionHistory> listAll = transactionHistoryService.getListTransactionRequestByAdminReport();
		HashSet<String> set = new HashSet<String>();

		for (TransactionHistory trans : listAll) {
			set.add(trans.getAccImpact().getAccountFirstName());
		}
		return set;
	}

}
